package com.heatup.apt.management.service.course.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.heatup.apt.common.dao.*;
import com.heatup.apt.model.course.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.heatup.apt.common.constants.OrderContants;
import com.heatup.apt.common.constants.CourseConstants.CourseType;
import com.heatup.apt.common.util.DateUtils;
import com.heatup.apt.management.service.TemplateSendService;
import com.heatup.apt.management.service.course.CourseTeamService;
import com.heatup.apt.model.Resource;
import com.heatup.apt.model.ResourceExample;
import com.heatup.apt.model.api.OrderInfoResultModel;
import com.heatup.apt.model.product.ServicePrice;
import com.heatup.apt.model.product.ServicePriceExample;

@Service
public class CourseTeamServiceImpl implements CourseTeamService {
	private Logger logger = LoggerFactory.getLogger(CourseTeamServiceImpl.class);

	@Autowired
	private CourseInfoMapper courseInfoMapper;
	@Autowired
	private CourseScheduleMapper courseScheduleMapper;
	@Autowired
	private CourseCoachMapper courseCoachMapper;
	@Autowired
	private CourseStoreMapper courseStoreMapper;
	@Autowired
	private ResourceMapper resourceMapper;
	@Autowired
	private ServicePriceMapper servicePriceMapper;
	@Autowired 
	private OrderInfoResultMapper orderInfoResultMapper;
	@Autowired
	private OrderInfoMapper orderInfoMapper;
	@Autowired
	private TemplateSendService templateSendService;
	@Autowired
	private CourseSignMapper courseSignMapper;

	/**
	 * 团体课程保存
	 */
	@Override
	public boolean saveCourseTeamInfo(CourseTeamResultModel courseTeamResultModel) {
		logger.info("============The Method saveCourseTeamInfo is begin ===================");
		Integer courseId = courseTeamResultModel.getId();
		int count = -1;
		// 保存和编辑
		
		String courseAttr = courseTeamResultModel.getCourseAttr();
		courseAttr = courseAttr.replaceAll(",", "#");
		courseTeamResultModel.setCourseAttr(courseAttr);
		Integer serviceId=null;
		
		if (courseId != null) {
			// 更新
			//查询存在的记录，如果课程最大人数有限制，则需要增加排队人数变化的判断。
			CourseTeamResultModel courseTeamResultModelOld = findCourseTeamResultModelById(courseTeamResultModel.getId());
		
			//更新价格
			ServicePriceExample servicePriceExample = new ServicePriceExample();
			servicePriceExample.or().andCourseIdEqualTo(courseId).andServiceTypeEqualTo(1);
			List<ServicePrice> servicePrices =	servicePriceMapper.selectByExample(servicePriceExample);
			ServicePrice oldServicePrice = null;
			
			//更新
			if(servicePrices!=null) {
				oldServicePrice=servicePrices.get(0);
				
				oldServicePrice.setPrimePrice(courseTeamResultModel.getServicePrice().getPrimePrice());
				oldServicePrice.setPrice(courseTeamResultModel.getServicePrice().getPrice());
				oldServicePrice.setStoreId(Integer.valueOf(courseTeamResultModel.getStoreId()));
				oldServicePrice.setServiceName(courseTeamResultModel.getTitle());
				serviceId=oldServicePrice.getId();
			
				servicePriceMapper.updateByPrimaryKey(oldServicePrice);
				//servicePriceMapper.updateByPrimaryKey(oldServicePrice);
			}else{
				oldServicePrice= new ServicePrice();
				oldServicePrice.setCourseId(courseId);
				oldServicePrice.setPrimePrice(courseTeamResultModel.getServicePrice().getPrimePrice());
				oldServicePrice.setPrice(courseTeamResultModel.getServicePrice().getPrice());
				oldServicePrice.setServiceName(courseTeamResultModel.getTitle());
				oldServicePrice.setServiceType(CourseType.team_course.getIndex());
				oldServicePrice.setLevel(1);
				oldServicePrice.setStoreId(Integer.valueOf(courseTeamResultModel.getStoreId()));
				oldServicePrice.setDuration(courseTeamResultModel.getPeriods()); // 私教这里：Periods与Duration一样
				serviceId=	servicePriceMapper.insertSelective(oldServicePrice);
			}
			
			//删除课程相关信息
			courseCoachMapper.deleteByCourseId(courseId);
			courseStoreMapper.deleteByCourseId(courseId);
			addCourseSignList(courseTeamResultModel,2);

			ResourceExample resourceExample = new ResourceExample();
			resourceExample.or().andParentIdEqualTo(courseId).andParentTypeEqualTo("2");
			resourceMapper.deleteByExample(resourceExample);
			
			// 2. 如果 课程最大人数有变化，则触发排队的订单是否要变成正常订单
			if (courseTeamResultModelOld != null) {
				if (courseTeamResultModel.getMaxCount().compareTo(courseTeamResultModelOld.getMaxCount()) > 0) {
					int waitCount = courseTeamResultModelOld.getWaitCount() == null ? 0: courseTeamResultModelOld.getWaitCount();
					int currentCount = courseTeamResultModelOld.getCurrentCount() == null ? 0: courseTeamResultModelOld.getCurrentCount();
					// 查询所有排队的订单
					List<OrderInfoResultModel> waitOrders = orderInfoResultMapper.selectWaitOrderByServiceId(serviceId);
					if (waitOrders != null && waitOrders.size() > 0) {
						int personCount = 0;
						for (OrderInfoResultModel waitOrder : waitOrders) {
							// 当前订单人数
							int curOrderPersonCount = (waitOrder.getOrderDetail().getPersonCount() == null ? 0: waitOrder.getOrderDetail().getPersonCount());
							personCount += curOrderPersonCount;
							// 当前课程的人数应该增加
							currentCount = currentCount + curOrderPersonCount;
							waitCount -= curOrderPersonCount;
							// 将排队等待的订单更新成预订成功
							waitOrder.setOrderStatus(OrderContants.OrderStatus.NORMAL.getStatus());
							waitOrder.setUpdatedBy(-1);
							waitOrder.setUpdatedTime(new Date());
							orderInfoMapper.updateSelectiveById(waitOrder);
							templateSendService.sendBookingSuccTemplateMsg(waitOrder.getId(),
									waitOrder.getOrderStatus());
							if (personCount >= (courseTeamResultModel.getMaxCount()
									- courseTeamResultModelOld.getMaxCount())) {
								break;
							}
						}
						courseTeamResultModel.setCurrentCount(currentCount);
						courseTeamResultModel.setWaitCount(waitCount);
					}
				}
			}
			
			courseInfoMapper.updateSelectiveById(courseTeamResultModel);
			courseScheduleMapper.deleteByCourseId(courseId);
			
			
		} else {
			// 新增
			count = courseInfoMapper.insertSelective(courseTeamResultModel);
			courseId = courseTeamResultModel.getId();
			if (count > 0) {
				// 保存价格
				ServicePrice servicePrice = new ServicePrice();
				servicePrice.setCourseId(courseId);
				servicePrice.setPrimePrice(courseTeamResultModel.getServicePrice().getPrimePrice());
				servicePrice.setPrice(courseTeamResultModel.getServicePrice().getPrice());
				servicePrice.setServiceName(courseTeamResultModel.getTitle().trim());
				servicePrice.setServiceType(CourseType.team_course.getIndex());
				servicePrice.setLevel(1);
				servicePrice.setStoreId(Integer.valueOf(courseTeamResultModel.getStoreId()));
				servicePrice.setDuration(courseTeamResultModel.getPeriods()); // 私教这里：Periods与Duration一样
				servicePriceMapper.insertSelective(servicePrice);

				// 课程计划
				addCourseSignList(courseTeamResultModel,1);
			}else{
				return false;
			}

		}
		
		// 课程计划
		String startDate = courseTeamResultModel.getStartDate();
		String startTime = courseTeamResultModel.getStartTime();
		String endTime = courseTeamResultModel.getEndTime();
		CourseSchedule courseSchedule = new CourseSchedule();
		
		if(startDate.indexOf("/")>0){
			String[] strD = startDate.split("/");
			startDate = strD[2] + "-" + strD[0] + "-" + strD[1];
			}
		
		try {
			courseSchedule.setStartTime(
					DateUtils.toDate(startDate + " " + startTime + ":00", DateUtils.datePatternAllHH));
			courseSchedule.setEndTime(
					DateUtils.toDate(startDate + " " + endTime + ":00", DateUtils.datePatternAllHH));
			SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			String fromDate = simpleFormat.format(courseSchedule.getStartTime());
			String toDate = simpleFormat.format(courseSchedule.getEndTime());
			long from = simpleFormat.parse(fromDate).getTime();
			long to = simpleFormat.parse(toDate).getTime();
			int minutes = (int) ((to - from) / (1000 * 60));
			courseSchedule.setDuration(minutes);
			courseSchedule.setHourMin(startTime + "~" + endTime);
			courseSchedule.setCourseId(courseId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		courseScheduleMapper.insertSelective(courseSchedule);
		
		// 课程教练信息
		CourseCoach courseCoach = courseTeamResultModel.getCourseCoach();
		courseCoach.setCourseId(courseId);
		courseCoach.setIsMain("1");
		courseCoachMapper.insertSelective(courseCoach);

		// 保存课程门店信息
		String courseStores = courseTeamResultModel.getStoreId();
		String[] courseStoreId = courseStores.split(",");

		CourseStore courseStore;
		for (String cs : courseStoreId) {
			courseStore = new CourseStore();
			courseStore.setStoreId(Integer.valueOf(cs));
			courseStore.setCourseId(courseId);
			courseStoreMapper.insertSelective(courseStore);
		}

		// 课程计划

//		// 保存二维码图片地址 教练二维码 现在由教练表直接读取 blank May 5 2017
//
//		if (StringUtils.isNotBlank(courseTeamResultModel.getQunQRCodePic())) {
//			Resource qunQRCodeResource = new Resource();
//			qunQRCodeResource.setParentType("2");
//			qunQRCodeResource.setParentId(courseId);
//			qunQRCodeResource.setResType("1");
//			qunQRCodeResource.setResKey("QRCode");// QR二维码
//			qunQRCodeResource.setTitle("团体课的二维码");
//			qunQRCodeResource.setUrl(courseTeamResultModel.getQunQRCodePic());
//			resourceMapper.insertSelective(qunQRCodeResource);
//		}
		// 保存视频封面地址
		if (StringUtils.isNotBlank(courseTeamResultModel.getLink())) {
			Resource videoResource = new Resource();
			videoResource.setParentId(courseId);
			videoResource.setParentType("2");
			videoResource.setResType("2");
			videoResource.setUrl(courseTeamResultModel.getUrl());
			videoResource.setLink(courseTeamResultModel.getLink());
			videoResource.setResKey("team_video");// 视频预览
			resourceMapper.insertSelective(videoResource);

		}
		// 保存类别照片地址
		String catePic = courseTeamResultModel.getCategoryPic();
		if (catePic.length() > 0) {
			String[] catePics = catePic.split(",");
			Resource catePicResource;
			for (String pic : catePics) {
				catePicResource = new Resource();
				catePicResource.setParentId(courseId);
				catePicResource.setParentType("2");
				catePicResource.setResType("1");
				catePicResource.setUrl(pic);
				catePicResource.setResKey("team_category");
				resourceMapper.insertSelective(catePicResource);
			}

		}

		return true;
	}

	/**
	 * 根据ID团体课程信息
	 * 
	 * @param courseId
	 * @return
	 */
	public CourseTeamResultModel findCourseTeamResultModelById(int courseId) {

		CourseTeamResultModel courseTeamResultModel = courseInfoMapper.queryCourseTeamResultById(courseId);

		if (courseTeamResultModel != null) {
			String startTime="";
			String endTime="";
			if(courseTeamResultModel.getHourMin()!=null){
				String[] hourMins = courseTeamResultModel.getHourMin().split("~");
				startTime=hourMins[0];
				endTime = hourMins[1];
			}
			courseTeamResultModel.setStartTime(startTime);
			courseTeamResultModel.setEndTime(endTime);

			ResourceExample resourceExample = new ResourceExample();
			resourceExample.or().andParentIdEqualTo(courseId).andParentTypeEqualTo("2");
			List<Resource> resources = resourceMapper.selectByExample(resourceExample);
			if (resources != null && resources.size() > 0) {
				StringBuilder sCatePic = new StringBuilder();
				for (Resource resource : resources) {
					if (StringUtils.isNotBlank(resource.getResKey())
							&& resource.getResKey().equalsIgnoreCase("QRCode")) {
						courseTeamResultModel.setQunQRCodePic(resource.getUrl());
					}
					if (StringUtils.isNotBlank(resource.getResKey())
							&& resource.getResKey().equalsIgnoreCase("team_video")) {
						courseTeamResultModel.setUrl(resource.getUrl());
						courseTeamResultModel.setLink(resource.getLink());
					}
					if (StringUtils.isNotBlank(resource.getResKey())
							&& resource.getResKey().equalsIgnoreCase("team_category")) {
						if (sCatePic.length() <= 0) {
							sCatePic.append(resource.getUrl());
						} else {
							sCatePic.append("," + resource.getUrl());
						}
					}
				}
				if (sCatePic.length() > 0) {
					courseTeamResultModel.setCategoryPic(sCatePic.toString());
				}
			}
			return courseTeamResultModel;
		} else {
			return null;
		}

	}

	/**
	 *@Author: timo
	 *@Date: 2018/3/25 20:20
	 *@Description: 团课添加日程 也就是签到表
	 *@param model 课程基本信息
	 *@param type 1 表示新增 2 表示更新
	 */
	public void addCourseSignList(CourseTeamResultModel model, Integer type ){

		if (type == 2){
			// 需要删除在新增
			courseSignMapper.delCourseSginByCourseId(model.getId());
		}
		CourseSign courseSign = new CourseSign();
		try {

			courseSign.setStartTime(DateUtils.toDate(model.getStartDate() + " " + model.getStartTime() + ":00", DateUtils.datePatternAllHH));
			courseSign.setEndTime(DateUtils.toDate(model.getStartDate() + " " + model.getEndTime() + ":00", DateUtils.datePatternAllHH));
		}catch (Exception e){

		}
		courseSign.setCourseId(model.getId());
		courseSign.setCoachId(Long.valueOf(model.getCourseCoach().getCoachId()));//
		courseSign.setCourseName(model.getTitle());
		courseSign.setCourseNumber(1);
		courseSign.setCourseSortNum(1);
		courseSign.setPeriods(model.getPeriods());
		courseSign.setStoreId(Integer.valueOf(model.getStoreId()));

		courseSign.setStatus(1);
		courseSign.setSignType(1);
		courseSignMapper.insertSelective(courseSign);
	}

}
